import { apiCity } from "@/api/apiConfig";
import { apiConfigCurrent, apiConfigcv } from "@/api/apiCommon";
import { setStorageSync, getStorageSync } from "@/utils/storageUtils";
import {
  dateToTimestamp,
  formatTimestamp,
  parseTimeArray,
  formatDateV1,
} from "@/utils/datetimeUtil";
import {
  getToken,
  setToken,
  removeToken,
  setUserinfo,
  getUserinfo,
} from "@/utils/auth";
import md5 from "js-md5";
import {
  isNullOrEmpty,
  toEscapedJsonString,
  fromEscapedJsonString,
  assignFormParams,
} from "@/utils/common";

// 表单里数组格式的KEY
var form_array_keys = [
  "credit_status",
  "sesame_scores",
  "huabei_quotas",
  "baitiao_quotas",
  "works",
  "regions",
  "region_blocks",
  "channel_ids",
  "loan_count_1_month",
  "loan_performance_count_1m",
  "loan_amount_1_month",
  "loan_performance_amount_1m",
  "loan_count_3_months",
  "loan_performance_count_3m",
  "loan_amount_3_months",
  "loan_performance_amount_3m",
];

var userinfo = null;
var citys = null;
var config_current = null;
var is_debug = true;

// 获取表格的文本
export function getTableText(key, value) {
  const data = {
    "0,600": "600以下",
    "600,649": "600-649",
    "650,699": "650-699",
    "700,max": "700以上",
    nationwide: "全国",
    region: "地区",
    no: "无",
    "0,5000": "0-5000",
    "5000,max": "5000以上",
    1: "有",
    0: "无",
    not_communicated: "未沟通",
    different_location_order: "异地订单",
    not_connected: "未接通",
    connected_no_intent: "接通无意向",
    connected_with_intent: "接通有意向",
    invalid_number: "无效号码",
    connected_and_added: "接通并加微信",
    premium_user: "会员用户",
    current_overdue: "当前有逾期",
    overdue_cleared: "逾期已结清",
    no_overdue: "无逾期",
    // "": "",
    // "": "",
  };

  return data[value] || value;
}

// 获取城市
export async function getCity() {
  return new Promise((resolve, reject) => {
    if (citys) {
      resolve(citys);
      return;
    }

    var city = getStorageSync("city_data", false);
    if (city) {
      citys = city;
      resolve(city);
      return;
    }
    apiCity({}).then((response) => {
      const result = response.data;
      var city = result.city;
      setStorageSync("city_data", city);
      citys = city;
      resolve(city);
      return;
    });
  });
}

// 获取通用配置
export async function getConfigCurrent() {
  return new Promise((resolve, reject) => {
    if (config_current) {
      // log('获取通用配置1', config_current)
      resolve(config_current);
      return;
    }

    const currentMinute = new Date().getMinutes();
    if (currentMinute % 10 !== 0) {
      var config_current_currentMinute = getStorageSync(
        "config_current_currentMinute",
        false
      );
      if (config_current_currentMinute != currentMinute) {
        config_current = getStorageSync("config_current", false);
        if (config_current) {
          // log('获取通用配置2', config_current)
          setStorageSync("config_current_currentMinute", currentMinute);
          resolve(config_current);
          return;
        }
      }
    }
    apiConfigcv().then((response) => {
      if (response["code"] == 0) {
        resolve([]);
        return;
      }
      var v = response["data"]["v"];
      config_current = getStorageSync("config_current", false);
      if (v == config_current["v"]) {
        resolve(config_current);
        return;
      } else {
        apiConfigCurrent({}).then((response) => {
          config_current = response.data;
          setStorageSync("config_current", config_current);
          resolve(config_current);
          return;
        });
      }
    });
  });
}

// 获取用户ID
export function getUserId() {
  var userinfo = getUserinfo();
  return userinfo["id"];
}

// 转换工作
export function trWokeText(id, config_productCluePlan) {
  // 参数校验
  if (typeof id !== "string" || !id) {
    console.error("trWokeText: id 参数必须是非空字符串");
    return "未知状态"; // 返回默认信息
  }
  if (
    typeof config_productCluePlan !== "object" ||
    config_productCluePlan === null
  ) {
    console.error("trWokeText: config_productCluePlan 参数必须是有效的对象");
    return "未知状态"; // 返回默认信息
  }
  // 返回对应的中文文本，若未找到则返回默认信息
  return config_productCluePlan[id] || "未知状态";
}

// 转换城市单个
export function trCityItem(data, num, type) {
  // console.log(num, 'num');
  // 检查参数合法性
  if (!Array.isArray(data)) {
    console.error("Invalid data: Expected an array of city data");
    throw new Error("Invalid data: Expected an array of city data");
  }
  if (typeof num !== "string" && typeof num !== "number") {
    console.error("Invalid num: Expected a string or number");
    throw new Error("Invalid num: Expected a string or number");
  }
  if (["province", "city", "district"].indexOf(type) === -1) {
    console.error('Invalid type: Expected "province", "city", or "district"');
    throw new Error('Invalid type: Expected "province", "city", or "district"');
  }

  // console.log([data, num, type,'========='])

  // 遍历函数，递归查找指定的城市
  for (let item of data) {
    // 省级判断
    if (type === "province" && item.value === num) {
      return item.label;
    }
    // 市级判断
    if (item.children && (type === "city" || type === "district")) {
      for (let city of item.children) {
        if (type === "city" && city.value === num) {
          return city.label;
        }
        // 区县级判断
        if (type === "district" && city.children) {
          for (let district of city.children) {
            if (district.value === num) {
              return district.label;
            }
          }
        }
      }
    }
  }

  return num; // 如果没有匹配，返回 num
}

// 转成城市
export function trCity(data, codesToMatch) {
  // 如果 codesToMatch 是字符串，按逗号分割成数组
  if (typeof codesToMatch === "string") {
    codesToMatch = codesToMatch.split(",");
  }
  let provinceName = "";
  let cityName = "";
  let areaName = "";
  for (let i = 0; i < data.length; i++) {
    if (data[i].value == codesToMatch[0]) {
      provinceName = data[i].label;
      for (let j = 0; j < data[i].children.length; j++) {
        if (data[i].children[j].value == codesToMatch[1]) {
          cityName = data[i].children[j].label;
          for (let k = 0; k < data[i].children[j].children.length; k++) {
            if (data[i].children[j].children[k].value == codesToMatch[2]) {
              areaName = data[i].children[j].children[k].label;
              break;
            }
          }
          break;
        }
      }
      break;
    }
  }
  var ret = [provinceName, cityName ? cityName : "", areaName ? areaName : ""];
  return ret.join();
}

// 获取初始化表格数据
export function initTableData() {
  return {
    current_page: 1,
    data: [],
    last_page: 1,
    per_page: "15",
    total: 0,
  };
}

// 获取初始化时间区间选择器
export function initPickerOptions() {
  return {
    shortcuts: [
      {
        text: "最近一周",
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          picker.$emit("pick", [start, end]);
        },
      },
      {
        text: "最近一个月",
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          picker.$emit("pick", [start, end]);
        },
      },
      {
        text: "最近三个月",
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          picker.$emit("pick", [start, end]);
        },
      },
    ],
  };
}

/** 权限判断 */
export function authJudgment(agree_group) {
  var userinfo = getUser();
  var group_key = userinfo.group_key;
  if (!Array.isArray(agree_group)) {
    agree_group = [agree_group];
  }
  if (agree_group.indexOf(group_key) > -1) {
    return true;
  } else {
    return false;
  }
  console.log([agree_group, userinfo]);
}

// 获取用户数据
export function getUser() {
  if (userinfo) {
    return userinfo;
  }
  userinfo = getUserinfo();
  return userinfo;
}

// 清空用户数据
export function clearUser() {
  userinfo = null;
}

// 刷新用户数据
export function refreshUser() {
  userinfo = getUserinfo();
}

// 列表城市转换
export function cityAssignValueToList(list, key, city) {
  console.log(list, "list");
  list.forEach((item) => {
    if (typeof item === "object" && item !== null) {
      // 检查 item 是否为对象
      item[key] = trCity(city, item[key]);
    }
  });
  return list;
}

/** 加工 - 请求参数 */
export async function processParams(params) {
  return new Promise((resolve, reject) => {
    Object.entries(params).forEach(([key, value]) => {
      /** 判断数据是否为空 */
      if (isNullOrEmpty(value)) {
        delete params[key];
        return;
      } else if (key == "time_interval") {
        var start_date = params["time_interval"][0];
        var end_date = params["time_interval"][1];
        // console.log(start_date, 'start_date')
        params["start_time"] = dateToTimestamp(start_date);
        params["end_time"] = dateToTimestamp(end_date);
        delete params[key];
        return;
      } else if (key == "initpage") {
        if (params[key]) {
          params["page"] = 1;
        } else {
          delete params[key];
          return;
        }
      } else {
        params[key] = value;
      }
    });
    resolve(params);
  });
}

/** 加工 - 返回数据 */
export async function processResult(result, url = "") {
  return new Promise((resolve, reject) => {
    getConfigCurrent().then((response) => {
      // var config_current = response;
      if (result["datalist"]) {
        var list = result["datalist"]["data"] || result["datalist"];
        list = processDatalist(list, url);
        result["datalist"]["data"] = list;
      }
      if (result["details"]) {
        result["details"] = processDetails(result["details"]);
      }
      resolve(result);
    });
  });
}

/** 加工 详情数据 */
export function processDetails(formData) {
  var ignore_key = ["advertising_federated_login", "uv"];
  Object.entries(formData).forEach(([key, value]) => {
    // console.log(key, 'keykeykeykeykeykey')
    // 时间小时分 区间 转换
    if (key == "control_time") {
      value = fromEscapedJsonString(value);
      if (value) {
        var control_time_key_one = "monday_to_friday";
        if (
          isNullOrEmpty(value[control_time_key_one]["temporal_interval"][0])
        ) {
          value[control_time_key_one]["temporal_interval"] = [
            new Date(2024, 8, 5, 9, 0),
            new Date(2024, 8, 5, 18, 0),
          ];
        } else {
          value[control_time_key_one]["temporal_interval"] = parseTimeArray(
            value[control_time_key_one]["temporal_interval"]
          );
        }

        control_time_key_one = "saturday";
        if (
          isNullOrEmpty(value[control_time_key_one]["temporal_interval"][0])
        ) {
          value[control_time_key_one]["temporal_interval"] = [
            new Date(2024, 8, 5, 9, 0),
            new Date(2024, 8, 5, 18, 0),
          ];
        } else {
          value[control_time_key_one]["temporal_interval"] = parseTimeArray(
            value[control_time_key_one]["temporal_interval"]
          );
        }

        control_time_key_one = "sunday";
        if (
          isNullOrEmpty(value[control_time_key_one]["temporal_interval"][0])
        ) {
          value[control_time_key_one]["temporal_interval"] = [
            new Date(2024, 8, 5, 9, 0),
            new Date(2024, 8, 5, 18, 0),
          ];
        } else {
          value[control_time_key_one]["temporal_interval"] = parseTimeArray(
            value[control_time_key_one]["temporal_interval"]
          );
        }
      } else {
        value = {
          monday_to_friday: {
            temporal_interval: [
              new Date(2024, 8, 5, 9, 0),
              new Date(2024, 8, 5, 18, 0),
            ],
            status: false,
          },
          saturday: {
            temporal_interval: [
              new Date(2024, 8, 5, 9, 0),
              new Date(2024, 8, 5, 18, 0),
            ],
            status: false,
          },
          sunday: {
            temporal_interval: [
              new Date(2024, 8, 5, 9, 0),
              new Date(2024, 8, 5, 18, 0),
            ],
            status: false,
          },
        };
      }
    } else if (form_array_keys.includes(key)) {
      value = fromEscapedJsonString(value);
    } else if (
      [
        "loan_count_1_month",
        "loan_performance_count_1m",
        "loan_amount_1_month",
        "loan_performance_amount_1m",
        "loan_count_3_months",
        "loan_performance_count_3m",
        "loan_amount_3_months",
        "loan_performance_amount_3m",
      ].includes(key)
    ) {
      if (value) {
        value = fromEscapedJsonString(value);
      } else {
        value = {
          min: 0,
          max: 99999999,
        };
      }
    } else if (
      [
        "overdue_loan_count_m0_6m_status",
        "overdue_loan_count_m0_12m_status",
      ].includes(key)
    ) {
      if (isNullOrEmpty(value)) {
        value = 0;
      }
    }
    formData[key] = value;
  });
  return formData;
}

/** 加工 数据列表 */
export function processDatalist(list, url) {
  // log(list, 'listlistlist');
  list.forEach((obj) => {
    obj = processDatalistItem(obj, url);
  });
  return list;
}

/** 加工 数据列表 一项 */
export function processDatalistItem(obj, url = "") {
  // log(url, 'urlurl')
  // log(config_current, 'config_current');
  if (!config_current) {
    console.error("config_current null");
    return obj;
  }
  var config_city = config_current["city"];
  var config_product_clue_plan = config_current["clue"]["product_clue_plan"];
  var config_work = config_current["clue"]["work"];
  var clue = config_current["clue"];
  var clue_stage = clue["stage"];
  var channel = config_current["channel"];
  var ignore_key = ["advertising_federated_login1", "uv"];
  for (const key in obj) {
    if (ignore_key.includes(key)) {
      continue;
    }
    if (obj[key] === null || obj[key] === undefined || obj[key] === "") {
      continue;
    }
    if (key == "region") {
      obj[key] = trCity(config_city, obj["region"]);
    } else if (key == "createtime") {
      obj[key] = formatTimestamp(obj[key]);
    } else if (key == "province") {
      obj["province"] = trCityItem(config_city, obj["province"], "province");
    } else if (key == "city") {
      obj["city"] = trCityItem(config_city, obj["city"], "city");
    } else if (key == "district") {
      obj["district"] = trCityItem(config_city, obj["district"], "district");
    } else if (key == "work") {
      obj[key] = trWokeText(obj[key], config_work);
    } else if (key == "matching_status") {
      if (obj[key] == 1) {
        obj[key] = "通过";
      } else {
        obj[key] = obj["fail_msg"];
      }
    } else if (key == "clue_push_success_rate") {
      obj[key] = obj[key] + "%";
    } else if (key == "clue_register_rate") {
      obj[key] = obj[key] + "%";
    } else if (key == "channel_calculation_type") {
      obj[key] = processDataMatchingKeyValue(obj[key], channel["type_v1"]);
    } else if (key == "calculation_type") {
      obj[key] = processDataMatchingKeyValue(
        obj[key],
        channel["type_v1"],
        "value",
        "label"
      );
    } else if (key == "loan_type") {
      obj[key] = getTableText(key, obj[key]);
    } else if (key == "pc_plan") {
      obj[key] = processDataMatchingV2(obj[key], clue["product_clue_plan"]);
    } else if (key == "product") {
      obj[key]["loan_type"] = getTableText(key, obj[key]["loan_type"]);
    } else if (key == "clue") {
      obj[key] = processDatalistItem(obj[key]);
    } else if (key == "sesame_score") {
      obj[key] = getTableText(key, obj[key]);
    } else if (key == "huabei_quota") {
      obj[key] = getTableText(key, obj[key]);
    } else if (key == "baitiao_quota") {
      obj[key] = getTableText(key, obj[key]);
    } else if (key == "credit_status") {
      obj[key] = getTableText(key, obj[key]);
    } else if (key == "gender") {
      if (obj[key] == 1) {
        obj[key] = "男";
      } else if (obj[key] == 2) {
        obj[key] = "女";
      } else {
        obj[key] = "未知";
      }
    } else if (
      [
        "car",
        "house",
        "accumulation_fund",
        "social_security",
        "insurance",
        "business_owner",
      ].includes(key)
    ) {
      if (obj[key] == 1) {
        obj[key] = "有";
      } else if (obj[key] == 0) {
        obj[key] = "无";
      }
    } else if (key == "stage") {
      obj[key] = processDataMatchingKeyValue(obj[key], clue_stage);
    }
  }
  return obj;
}

/** 加工线索数据 */
export function processClue() {
  list.forEach((obj) => {
    for (const key in obj) {
      if (obj[key] === null || obj[key] === undefined || obj[key] === "") {
        continue;
      }
      if (key == "region") {
      }
    }
  });
}

// 加工 数据匹配
export function processDataMatching(data, config, key = "label") {
  log([data, config, key]);
  var matcData = config[data][key];
  return matcData;
}

// 加工 数据匹配  Key=>value
export function processDataMatchingKeyValue(
  data,
  config,
  key = "value",
  value = "label"
) {
  // log([data, config, key, value]);
  for (const k in config) {
    // log([config[k][key], data]);
    if (config[k][key] == data) {
      return config[k][value];
    }
  }
  return "未知";
}

// 加工 数据匹配 V2
export function processDataMatchingV2(data, config) {
  var matcData = config[data];
  return matcData;
}

/** 加工 - 表格参数 */
export async function processTableParams(tableParams) {
  return new Promise((resolve, reject) => {
    Object.entries(tableParams).forEach(([key, value]) => {
      console.log([key, value], "===");
      /** 判断数据是否为空 */
      if (isNullOrEmpty(value)) {
        delete tableParams[key];
        return;
      } else if (key == "time_interval") {
        var start_date = tableParams["time_interval"][0];
        var end_date = tableParams["time_interval"][1];
        console.log(start_date, "start_date");
        tableParams["start_time"] = dateToTimestamp(start_date);
        tableParams["end_time"] = dateToTimestamp(end_date);
        delete tableParams[key];
        return;
      }
      tableParams[key] = value;
    });
    resolve(tableParams);
  });
}

/** 加工 - 表格数据 */
export async function processTableData(list) {
  return new Promise((resolve, reject) => {
    getConfigCurrent().then((response) => {
      var clue = response["clue"];
      var config_city = response["city"];
      var config_product_clue_plan = response["clue"]["product_clue_plan"];
      var config_work = response["clue"]["work"];
      list.forEach((obj) => {
        for (const key in obj) {
          if (obj[key] === null || obj[key] === undefined || obj[key] === "") {
            continue;
          }
          if (key == "region") {
            obj[key] = trCity(config_city, obj["region"]);
          } else if (key == "createtime") {
            console.log(key, "key");
            obj[key] = formatTimestamp(obj[key]);
          } else if (key == "province") {
            obj["province"] = trCityItem(
              config_city,
              obj["province"],
              "province"
            );
          } else if (key == "city") {
            obj["city"] = trCityItem(config_city, obj["city"], "city");
          } else if (key == "district") {
            obj["district"] = trCityItem(
              config_city,
              obj["district"],
              "district"
            );
          } else if (key == "work") {
            obj[key] = trWokeText(obj[key], config_work);
          } else if (key == "matching_status") {
            if (obj[key] == 1) {
              obj[key] = "通过";
            } else {
              obj[key] = obj["fail_msg"];
            }
          } else if (key == "product") {
            obj[key]["loan_type"] = getTableText(key, obj[key]["loan_type"]);
          } else if (key == "uv") {
          } else if (key == "pc_plan") {
            obj[key] = processDataMatching(obj[key], clue["product_clue_plan"]);
          } else {
            obj[key] = getTableText(key, obj[key]);
          }
        }
      });
      resolve(list);
    });
  });
}

/** 判断数组中是否存在指定的 key（大小写不敏感）
 * @param {Array} arr - 要检查的数组
 * @param {String} key - 要查找的 key
 * @returns {Boolean} - 如果数组中存在该 key 则返回 true，否则返回 false
 */
export async function checkKeyInArray(arr, key) {
  if (!Array.isArray(arr) || typeof key !== "string") {
    console.warn("请输入正确的数组和字符串类型的 key");
    return false;
  }
  log("checkKeyInArray");
  // 将 key 转为小写
  const lowerKey = key.toLowerCase();

  // 遍历数组，将每个值转为小写后与 key 比较
  return arr.some((item) => {
    if (typeof item === "string") {
      log([item.toLowerCase(), lowerKey]);
      return item.toLowerCase() === lowerKey;
    }
    return false;
  });
}

// 获取表格合计
export function App_getSummaries(param) {
  const { columns, data } = param;
  const sums = [];
  var summariesKey = [
    "balance",
    "today_cost",
    "total_cost",
    "product_count",
    "product_clue_price_sham",
    "product_clue_price_real",
    // '',
    // '',
    // '',
    // '',
    // '',
    // '',
    // '',
    // '',
    // ''
  ];
  // summariesKey.push('');
  // summariesKey.push('');
  // summariesKey.push('');
  // summariesKey.push('');
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
    }
    if (summariesKey.includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]));
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          }
        }, 0);
      }
    }
  });
  return sums;
}

/** 详情数据加工 */
export async function processDetailsFormData(formData) {
  return new Promise((resolve, reject) => {
    getConfigCurrent().then((response) => {
      var config_city = response["city"];
      var config_product_clue_plan = response["clue"]["product_clue_plan"];
      var config_work = response["clue"]["work"];
      Object.entries(formData).forEach(([key, value]) => {
        // 时间小时分 区间 转换
        if (key == "control_time") {
          value = fromEscapedJsonString(value);
          if (value) {
            var control_time_key_one = "monday_to_friday";
            if (
              isNullOrEmpty(value[control_time_key_one]["temporal_interval"][0])
            ) {
              value[control_time_key_one]["temporal_interval"] = [
                new Date(2024, 8, 5, 9, 0),
                new Date(2024, 8, 5, 18, 0),
              ];
            } else {
              value[control_time_key_one]["temporal_interval"] = parseTimeArray(
                value[control_time_key_one]["temporal_interval"]
              );
            }

            control_time_key_one = "saturday";
            if (
              isNullOrEmpty(value[control_time_key_one]["temporal_interval"][0])
            ) {
              value[control_time_key_one]["temporal_interval"] = [
                new Date(2024, 8, 5, 9, 0),
                new Date(2024, 8, 5, 18, 0),
              ];
            } else {
              value[control_time_key_one]["temporal_interval"] = parseTimeArray(
                value[control_time_key_one]["temporal_interval"]
              );
            }

            control_time_key_one = "sunday";
            if (
              isNullOrEmpty(value[control_time_key_one]["temporal_interval"][0])
            ) {
              value[control_time_key_one]["temporal_interval"] = [
                new Date(2024, 8, 5, 9, 0),
                new Date(2024, 8, 5, 18, 0),
              ];
            } else {
              value[control_time_key_one]["temporal_interval"] = parseTimeArray(
                value[control_time_key_one]["temporal_interval"]
              );
            }
          } else {
            value = {
              monday_to_friday: {
                temporal_interval: [
                  new Date(2024, 8, 5, 9, 0),
                  new Date(2024, 8, 5, 18, 0),
                ],
                status: false,
              },
              saturday: {
                temporal_interval: [
                  new Date(2024, 8, 5, 9, 0),
                  new Date(2024, 8, 5, 18, 0),
                ],
                status: false,
              },
              sunday: {
                temporal_interval: [
                  new Date(2024, 8, 5, 9, 0),
                  new Date(2024, 8, 5, 18, 0),
                ],
                status: false,
              },
            };
          }
        } else if (
          [
            "sesame_scores",
            "huabei_quotas",
            "baitiao_quotas",
            "works",
            "regions",
            "region_blocks",
            "channel_ids",
          ].includes(key)
        ) {
          value = fromEscapedJsonString(value);
        } else if (
          [
            "loan_count_1_month",
            "loan_performance_count_1m",
            "loan_amount_1_month",
            "loan_performance_amount_1m",
            "loan_count_3_months",
            "loan_performance_count_3m",
            "loan_amount_3_months",
            "loan_performance_amount_3m",
          ].includes(key)
        ) {
          if (value) {
            value = fromEscapedJsonString(value);
          } else {
            value = {
              min: 0,
              max: 99999999,
            };
          }
        } else if (
          [
            "overdue_loan_count_m0_6m_status",
            "overdue_loan_count_m0_12m_status",
          ].includes(key)
        ) {
          if (isNullOrEmpty(value)) {
            value = 0;
          }
        }
        formData[key] = value;
        // console.log(`键: ${key}, 值: ${value}`);
      });

      resolve(formData);
    });
  });
}

/** 表单数据加工 */
export async function processFormData(formData, form_id = "") {
  return new Promise((resolve, reject) => {
    getConfigCurrent().then((response) => {
      var config_city = response["city"];
      var config_product_clue_plan = response["clue"]["product_clue_plan"];
      var config_work = response["clue"]["work"];
      Object.entries(formData).forEach(([key, value]) => {
        /** 判断数据是否为空 */
        if (key == "real_price") {
          delete formData[key];
          return;
        } else if (key == "time_interval") {
          delete formData[key];
          return;
        }

        // 时间小时分 区间 转换
        if (key == "control_time") {
          console.log(value["monday_to_friday"]["temporal_interval"], "======");

          // 周一至周五
          value["monday_to_friday"]["temporal_interval"][0] = formatDateV1(
            value["monday_to_friday"]["temporal_interval"][0],
            "HH:mm"
          );
          value["monday_to_friday"]["temporal_interval"][1] = formatDateV1(
            value["monday_to_friday"]["temporal_interval"][1],
            "HH:mm"
          );
          // 周六
          value["saturday"]["temporal_interval"][0] = formatDateV1(
            value["saturday"]["temporal_interval"][0],
            "HH:mm"
          );
          value["saturday"]["temporal_interval"][1] = formatDateV1(
            value["saturday"]["temporal_interval"][1],
            "HH:mm"
          );
          // 周日
          value["sunday"]["temporal_interval"][0] = formatDateV1(
            value["sunday"]["temporal_interval"][0],
            "HH:mm"
          );
          value["sunday"]["temporal_interval"][1] = formatDateV1(
            value["sunday"]["temporal_interval"][1],
            "HH:mm"
          );
          value = toEscapedJsonString(value);
        } else if (form_array_keys.includes(key)) {
          value = toEscapedJsonString(value);
        }

        formData[key] = value;
        // console.log(`键: ${key}, 值: ${value}`);
      });
      resolve(formData);
    });
  });
}

/** 合并表单
 * @param {Object} target - 目标对象（将要被赋值的对象）
 * @param {Object} source - 源对象（包含要赋值的参数）
 */
export function assignmentForm(target, source) {
  if (isNullOrEmpty(source)) {
    return target;
  }
  for (const key in source) {
    if (source.hasOwnProperty(key)) {
      // 只赋值在目标对象中存在的键
      if (target.hasOwnProperty(key)) {
        // console.log(key,'keykeykeykeykeykey')
        target[key] = source[key];
      }
    }
  }
  return target;
}

// 判断产品的运行时间
export function isProductRunning(schedule) {
  const today = new Date();
  var day = today.getDay();
  day === 0 ? 7 : day;
  log(schedule, "schedule");
  var operation_status = false;
  var temporal_interval = [];
  var temporal_interval_status = false;
  const currentTime = today.getHours() * 60 + today.getMinutes(); // 转换为分钟
  if (day >= 1 && day <= 5) {
    temporal_interval = schedule["monday_to_friday"]["temporal_interval"];
    temporal_interval_status = schedule["monday_to_friday"]["status"];
  } else if (day == 6) {
    temporal_interval = schedule["saturday"]["temporal_interval"];
    temporal_interval_status = schedule["monday_to_friday"]["status"];
  } else {
    temporal_interval = schedule["sunday"]["temporal_interval"];
    temporal_interval_status = schedule["monday_to_friday"]["status"];
  }

  if (temporal_interval_status) {
    const [start, end] = temporal_interval.map((time) => {
      const [hours, minutes] = time.split(":").map(Number);
      return hours * 60 + minutes; // 转换为分钟
    });
    operation_status = currentTime >= start && currentTime <= end;
  }
  return operation_status;
}

/** 打印日志 */
export function log(title, content) {
  if (is_debug) {
    console.log(title, content);
  }
}
